import { debug, sys } from "cc";
import { CommonUI } from "../../../../[框架]/通用UI/CommonUI";
import TaskConfig from "../../Model/TaskConfig";
import { TaskDefine } from "../../Model/TaskDefine";
import { ADPlayRequest } from "../../Model/广告/ADPlayRequest";
import TaskProxy from "../TaskProxy";
import { Toast } from "../../../../[框架]/通用UI/Toast/Toast";


export default class ADController {

    public static _lastForceClickFailed: boolean = false;
    public static setLastForceClickFailed(value: boolean): void {
        this._lastForceClickFailed = value;
        Guyu.Log.error(`设置上次强点失败==>`, value);
    }

    public static get LastForceClickFailed() {
        Guyu.Log.error(`获取上次强点失败==>`, this._lastForceClickFailed);
        return this._lastForceClickFailed;
    }

    public static get taskConfig(): TaskConfig {
        return TaskProxy.inst.taskConfig;
    }

    public static async requestPlayAd(opt: {
        adUnitId: string,
        autoDestory: boolean //是否自动销毁
    }) {
        const { adUnitId, autoDestory } = opt;
        let req = new ADPlayRequest().update({
            adUnitId: adUnitId,
            status: "playing",
            adStartTime: Date.now(),
            requiresForcedClick: this.needForceClickByMode("all"),
        });
        if (req.requiresForcedClick) {
            let ok = await new Promise<boolean>(_ => {
                CommonUI.showModal({
                    showCancel: true,
                    content: TaskProxy.inst.taskConfig.force_click_tips,
                    success: (res) => {
                        return _(res.confirm);
                    }
                });
            });
            if (!ok) {
                req.setStatus("cancel");
                //点了取消 
                let need = req.requiresForcedClick;
                ADController.setLastForceClickFailed(need);
                return req;
            }
        }
        if (Guyu.RuntimeSDK.onH5) {
            req.updateStartTime();
            CommonUI.showLoading({ title: "模拟看广告5s" });
            await Guyu.Tools.wait(5000);
            CommonUI.hideLoading();
            req.status = "completed";
            req.updateEndTime();
            return req;
        }
        let ad = this.getAD(adUnitId, true);
        if (!ad) {
            Guyu.Log.error(`未找到广告位:adUnitId=${adUnitId}`);
            return;
        }
        let onAndroid = sys.os === sys.OS.ANDROID;
        if (!onAndroid) {
            //ios 拿不到 onHide/onShow 所以简单计算时间差就行了
            let res = await ad.playAd({
                showError: true,
                showLoading: true,
                onAdShow: () => {
                    req.updateStartTime();
                }
            });

            if (!res.success) {
                req.setStatus("failed");
                req.desc = res.errMsg;
                return req;
            }
            req.updateEndTime();
            req.setStatus("completed");
            req.desc = res.errMsg;
            if (autoDestory) {
                //播放完毕 释放广告对象
                Guyu.AdFactory.removeAd(adUnitId, true);
            }
            return req;
        }

        // 安卓平台使用onHide/onShow计算时间
        let forceTimeT1 = Date.now();
        let forceTimeT2 = Date.now();
        let onHide = () => {
            forceTimeT1 = Date.now();
        };
        let onShow = () => {
            forceTimeT2 = Date.now();
            let forceTimeDiff = forceTimeT2 - forceTimeT1;
            req.updateForceClickTime(forceTimeDiff);
            Guyu.Log.error(`计算的强点时间:${forceTimeDiff}ms`);
        };
        let wx = Guyu.AdapterManager.adapter.wx;
        if (wx) {
            wx.offHide(onHide);
            wx.onHide(onHide);
            wx.offShow(onShow);
            wx.onShow(onShow);
        }
        let res = await ad.playAd({
            showError: true,
            showLoading: true
        });
        if (autoDestory) {
            //播放完毕 释放广告对象
            Guyu.AdFactory.removeAd(adUnitId, true);
        }

        if (!res.success) {
            req.setStatus("failed");
        } else {
            req.setStatus("completed");
        }
        return req;
    }


    /**
     * 根据模式判断是否需要强制点击广告
     * @param mode - 模式：'all'表示是否需要强点根据所有任务已完成次数计算 
     *  'single' 强点根据根据单个任务已完成次数计算
     * @param taskId - 可选参数，单个任务模式下需要传入任务ID
     * @returns 返回是否需要强制点击广告的布尔值
     * @example
     * // 全部任务模式
     * const needClick = adController.needForceClickByMode('total');
     * // 单个任务模式
     * const needClick = adController.needForceClickByMode('single', 'task_123');
     */
    public static needForceClickByMode(mode: 'all' | 'single', taskId?: string): boolean {
        if (mode === 'all') {
            return this.needForceClickByTaskId();
        } else if (mode === 'single' && taskId) {
            return this.needForceClickByTaskId(taskId);
        }
        return false;
    }

    public static needForceClickByTaskId(taskId?: string): boolean {
        if (this.LastForceClickFailed) {
            Guyu.Log.error(`上次强点失败了，本次要求一定要强点！`);
            return true;
        }
        const totalCount = taskId ? this.getTaskFinishCount(taskId) : this.getTotalFinishCount();
        const forceClick = this.shouldForceClick(totalCount);
        return this.checkForceClickProbability(forceClick);
    }

    public static getAD(adUnitId: string, showLoading: boolean = false) {
        Guyu.Log.debug(`随机广告位:adUnitId=${adUnitId}`);
        if (showLoading) {
            Guyu.AdapterManager.adapter.ui.showLoading("加载广告");
        }
        let ad = Guyu.AdFactory.getAD({ adUnitId: adUnitId, init: true, disableFallbackSharePage: true });
        if (showLoading) {
            Guyu.AdapterManager.adapter.ui.hideLoading();
        }
        return ad;
    }

    private static getTaskFinishCount(taskId: string): number {
        const task = this.taskConfig.reward_task.find(t => t.m_task_id === taskId);
        return task ? task.m_finishCount : 0;
    }

    //是否需要强制点击广告内容
    private static getTotalFinishCount(): number {
        return this.taskConfig.reward_task.reduce((sum, taskVO) => sum + taskVO.m_finishCount, 0);
    }

    private static shouldForceClick(totalCount: number): boolean {
        return totalCount + 1 >= this.taskConfig.force_click_count;
    }

    private static checkForceClickProbability(forceClick: boolean): boolean {
        if (!forceClick) return false;
        const force_click_percent = Number(this.taskConfig.force_click_percent) || 0;
        const random = Math.random();
        const result = random <= force_click_percent;
        if (result) {
            Guyu.Log.warn(`强制点击状态: ${'需要强制点击'} | 随机值: ${random} <= 强制点击几率: ${force_click_percent}`);
        } else {
            Guyu.Log.debug(`强制点击状态: ${'不需要强制点击'} | 随机值: ${random} > 强制点击几率: ${force_click_percent}`);
        }
        return result;
    }

    public static get customAD(): Guyu.WXCustomAd | null {
        if (!Guyu.RuntimeSDK.onMiniGame) {
            return;
        }
        let id = this.taskConfig.banner_adunits;
        if (!id) {
            Guyu.Log.error(`ADControll customAD banner_adunits null `);
            return;
        }
        let ad = Guyu.AdFactory.getCustomAd({ adUnitId: id });
        return ad;
    }

    public static get m_插屏广告(): Guyu.WXInterstitialAd | null {
        if (!Guyu.RuntimeSDK.onMiniGame) {
            return;
        }
        let id = this.taskConfig.inset_adunits;
        if (!id) {
            Guyu.Log.error(`ADControll m_插屏广告 inset_adunits null `);
            return;
        }
        let ad = Guyu.AdFactory.getInterstitialAd({ adUnitId: id });
        return ad;
    }
}